<template>
  <el-dialog
  title="编辑"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
     width="50%"
     :fullscreen="full_screen"
    >
    <div class="app-container">
   <el-backtop />
    <el-form
    ref="dialogForm"
    :model="formData"
  >
  <el-button type="primary" class="isfullscreen" @click="full_screen=!full_screen">{{full_screen?'退出全屏':'全屏'}}</el-button>
  <el-row :gutter="12">
    <el-col style="width: inherit;min-width:70px;"><div class="grid-content bg-purple-light">
      <div style="margin-top: 2px;font-weight: bolder;margin-bottom: 7px;">文件名称</div>
      <div> {{formData.name}}</div>
      </div>
    </el-col>
    <el-col :span="8"><div class="grid-content bg-purple-light" style="margin-right: 5px;">
        <el-form-item prop="viewName" label="展示名称">
          <el-input v-model.trim="formData.viewName" placeholder="" clearable />
        </el-form-item>
      </div></el-col>
    <el-col :span="12"><div class="grid-content bg-purple">
          <el-form-item prop="description" label="描述">
            <el-input v-model.trim="formData.description" placeholder="" clearable style="width:100%" />
          </el-form-item>
      </div></el-col>
  </el-row>
    <el-form-item prop="content" label="文件内容">
      <div style="display: inline-block;margin-bottom: 5px;">
        <span class="split">|</span>
        <el-dropdown @command="changeCodeTheme">
          <span class="el-dropdown-link">
            代码样式<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item,index) in codeThemeList" :command="item" :key="index">{{ item }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span class="split">|</span>
        快捷键：<el-tag v-for="(item,index) in shortcutKeyList" effect="plain" size="mini" style="margin-right: 5px" :key="index">{{ item }}</el-tag>
      </div>
      <codemirror
        ref="editor"
        v-model="formData.content"
        :options="cmOptions"
      />
    </el-form-item>
  </el-form>
      
  </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
  
</template>

<style>
  .el-form-item--mini .el-form-item__content,
  .el-form-item--mini .el-form-item__label,
  .el-form-item__content {
   line-height: 20px;
  }
  .velocity-tip {
    color: #606266;
    font-size: 13px;
    font-weight: normal;
  }
  .velocity-var {
  }
  .velocity-var li {
    font-size: 14px;
    color: #606266;
    line-height: 26px;
  }
  .velocity-var a {
    color: #409EFF;
    font-weight: 500;
  }
  .velocity-var a:hover {
    color: rgba(64, 158, 255, 0.75);
  }
  .hasFix {
    position: fixed;
    top: 0;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  span.split {
    color: #ccc;
    margin: 0 3px;
  }
</style>

<script>
import { projectConfigupdate } from '@/api/article'
import { codemirror } from 'vue-codemirror'

import 'codemirror/theme/neat.css'
import "codemirror/theme/darcula.css";
import "codemirror/theme/material.css";

/** 搜索 替换框置顶*/
import 'codemirror/addon/scroll/annotatescrollbar.js'
import 'codemirror/addon/search/matchesonscrollbar.js'
import 'codemirror/addon/search/match-highlighter.js'
import 'codemirror/addon/search/jump-to-line.js'

import 'codemirror/addon/dialog/dialog.js'
import 'codemirror/addon/dialog/dialog.css'
import 'codemirror/addon/search/searchcursor.js'
import 'codemirror/addon/search/search.js'

require('codemirror/mode/velocity/velocity')


import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
require("codemirror/mode/clike/clike.js");
require("codemirror/addon/edit/closebrackets.js");

const TEMPLATE_CODE_THEME = 'gen.template.code.theme'

export default {
  components: { codemirror },
  props:{
    dialogVisible:{
      type:Boolean,
      default:false
    },
    editId:{
      type:Number,
      default:0
    }
  },
  data() {
    return {
      full_screen:false,
      codeThemeList: ['neat', 'darcula','material'],
      shortcutKeyList: [
        '保存(Ctrl+S)',
        '删除当行(Ctrl+D)',
        '复制当行(Ctrl+C)',
        '剪切当行(Ctrl+X)',
        '替换(Ctrl+Shift+F)'
      ],
      formData: {
        name: '',
        viewName: '',
        description: '',
        content: ''
      },
      formRules: {
        viewName: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      //code mirror配置
      cmOptions: {
        value: '',
        // mode: 'text/velocity',
        mode: 'text/x-java',
        theme: 'neat',
        lineNumbers: true,
        readOnly: false,
        tabSize: 4,  // tab的空格个数
        indentUnit: 2 ,  // 一个块（编辑语言中的含义）应缩进多少个空格
        autocorrect: true,  // 自动更正
        spellcheck: true,  // 拼写检查
        lint: true,  // 检查格式
        lineNumbers: true,  //是否显示行数
        lineWrapping: true, //是否自动换行
        styleActiveLine: true,  //line选择是是否高亮
        // keyMap: 'intellij',  // sublime编辑器效果
        matchBrackets: true,  //括号匹配
        autoCloseBrackets: true,  // 在键入时将自动关闭括号和引号
        matchTags: { bothTags: true },  // 将突出显示光标周围的标签
        foldGutter: true,  // 可将对象折叠，与下面的gutters一起使用
        gutters: [
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter"
        ],
        highlightSelectionMatches: {
          minChars: 2,
          style: "matchhighlight",
          showToken: true
        },
        hintOptions: {
          // 自定义提示选项
          completeSingle: false, // 当匹配只有一项的时候是否自动补全
          tables: {
          }, // 代码提示
        }
      },
      isVelocityBarFixed: false,
      // tree
      collapseActiveName: '0',
      needFix: false,
      keywordHelpShow: false
    }
  },
  created() {
    this.post(`/projectManage/projectConfig/info/${this.editId}`, {}, function(resp) {
      this.formData = resp.data
    })
    //初始化代码主题
    this.cmOptions.theme = this.getAttr(TEMPLATE_CODE_THEME) || 'neat'
  },
  mounted() {
    this.$nextTick(()=>{
       this.$refs.editor.codemirror.on('inputRead', (cm,event) => {
        const index=this.formData.name.lastIndexOf(".")
        const code=this.formData.name.slice(index)
        if(code===".java"){
            if(/^[a-zA-Z\.=]$/gi.test(event.text[0])){
              cm.showHint()
            }
        }
      })
    })
    window.addEventListener('scroll', this.handlerScroll)
    this.watchKeydown()
  },
  methods: {
    handleClose(){
       this.$parent.dialogVisible=false
    },
    refresh() {
        this.jsonEditor && this.jsonEditor.refresh();
    },
    watchKeydown(){
      let _this = this;
      document.onkeydown = function(e) {
        let key = window.event.keyCode;
        if (key== 83 && event.ctrlKey) {//s == 83 && event.ctrlKey
          window.event.preventDefault() //关闭浏览器快捷键
          _this.onSave();
        }
        if (event.ctrlKey && key == 82) {
          window.event.preventDefault() //关闭浏览器快捷键
        }

      };
    },
    handlerScroll() {
      const scrollTop = window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      this.needFix = scrollTop > 80
    },
    async onSave() {
        const res=await projectConfigupdate(this.formData)
        if(res?.code===200){
            this.$message({
                message: "编辑成功",
                type: 'success',
            })  
            //this.goRoute('itemListPath')
            this.$parent.projectConfigfindPage(this.$parent.peizhiId)
            this.handleClose()

        }
    },
    changeCodeTheme(theme){
      this.cmOptions.theme = theme
      this.setAttr(TEMPLATE_CODE_THEME,theme)
    }
  }
}
</script>
<style scoped lang="scss">
   ::v-deep .CodeMirror{
     height: inherit!important;
     border: 1px solid #eee !important;
  }
  ::v-deep .vue-codemirror{
     max-height:520px;
     overflow: auto;
  }
  .isfullscreen{
      position: absolute;
      right: 50px;
      top: 15px;
  }
</style>
